﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace JESAI.Common.Util
{
    public class HttpClientUtility
    {
        public static byte[] DownLoad(string uri)
        {
            //请求地址
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            //获取网络流
            Stream ns = request.GetResponse().GetResponseStream();
            byte[] buf = new byte[request.GetResponse().ContentLength];
            //获取文件实际长度
            long contentLength = request.GetResponse().ContentLength;
            int index = 0;
            while (true)
            {
                var length = ns.Read(buf, index, buf.Length - index);
                if (length == 0)
                    break;
                index = index + length;
            }
            request.Abort();
            ns.Close();
            ns.Dispose();
            return buf;
        }

        public static byte[] GetImageContentFromHttp(string http)
        {
            byte[] bytes;

            var request = (HttpWebRequest)WebRequest.Create(http);

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                var dd = response.ContentLength;
                if (response.StatusCode != HttpStatusCode.OK)
                {
                    var message = String.Format("请求失败，状态码：{0}", response.StatusCode);
                    throw new ApplicationException(message);
                }

                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream == null) return null;

                    using (MemoryStream fs = new MemoryStream())
                    {
                        try
                        {
                            byte[] buffer = new byte[1024];
                            while (true)
                            {
                                int sz = responseStream.Read(buffer, 0, 1024);
                                if (sz == 0) break;
                                fs.Write(buffer, 0, sz);
                            }
                            responseStream.Close();
                            fs.Position = 0;

                            bytes = new byte[(int)fs.Length];
                            fs.Read(bytes, 0, bytes.Length);
                            fs.Flush();
                            fs.Close();
                        }
                        catch (Exception)
                        {
                            fs.Close();
                            throw;
                        }
                    }
                }
            }

            return bytes;
        }
    }
}
